from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.generic.base import View

from apps.users.forms import LoginForm, DynamicLoginForm


class RegisterView(View):
    def get(self, request, *args, **kwargs):
        return render(request, "register.html")

    def post(self, request, *args, **kwargs):
        return render(request, "register.html")


class LoginView(View):
    """登录视图，基于类视图"""

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return HttpResponseRedirect(reverse("index"))
        login_form = DynamicLoginForm()
        return render(request, "login.html", {
            "login_form": login_form,
        })

    def post(self, request, *args, **kwargs):
        # username = request.POST.get("username", "")
        # password = request.POST.get("password", "")

        # 这种前端登录验证很冗余=>表单验证
        # if not username:
        #     return render(request, "login.html", {"msg": "请输入用户名"})
        # if not password:
        #     return render(request, "login.html", {"msg": "请输入密码"})
        # if len(password):
        #     return render(request, "login.html", {"msg": "密码格式不正确"})

        # 引出Forms表单验证 =>作用：1）表单验证；2)获取cleaned_data;3）表单回填
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            # 进行用户认证,通过用户名和密码查询用户是否存在<=数据库密码存储的是密文
            username = login_form.cleaned_data["username"]
            password = login_form.cleaned_data["password"]
            user = authenticate(username=username, password=password)
            if user is not None:  # 查询到用户
                login(request, user)
                # 登录成功后应该返回页面
                return HttpResponseRedirect(reverse("index"))
            # 未查询到用户
            return render(request, "login.html", {"msg": "用户名或密码错误", "login_form": login_form})
        return render(request, "login.html", {"login_form": login_form})


class LogoutView(View):
    def get(self, request, *args, **kwargs):
        logout(request)
        return HttpResponseRedirect(reverse("login"))
